package com.github.slowrookie.interceptor;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Date;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.springframework.util.ReflectionUtils;

import com.github.slowrookie.persistence.AuditablePersistable;

/**
 * Hibernate 拦截器
 * 
 * @author 刘佳兴
 */
public class AuditableInterceptor extends EmptyInterceptor{

	private static final long serialVersionUID = 1L;

	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		
		if(entity instanceof AuditablePersistable){
			if(((AuditablePersistable) entity).isNew()){
				((AuditablePersistable) entity).setCreatedBy(1L);
				((AuditablePersistable) entity).setLastModifiedBy(1L);
				((AuditablePersistable) entity).setCreatedDate(new Date());
				((AuditablePersistable) entity).setLastModifiedDate(new Date());
			}else{
				((AuditablePersistable) entity).setLastModifiedBy(1L);
				((AuditablePersistable) entity).setLastModifiedDate(new Date());
			}
			
			for (int i = 0; i < propertyNames.length; i++) {
				String propertyName = propertyNames[i];
				Method method = ReflectionUtils.findMethod(entity.getClass(), "get" + propertyName.substring(0, 1).toUpperCase().concat(propertyName.substring(1)));
				state[i] = ReflectionUtils.invokeMethod(method, entity);
			}
		}
		
		return super.onSave(entity, id, state, propertyNames, types);
	}

	
	
}
